package vip.lsjscl.demo.custom;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import vip.lsjscl.demo.common.manager.ExportTaskManager;
import vip.lsjscl.demo.common.manager.FileManager;
import vip.lsjscl.demo.common.model.ExportProgress;

import java.io.File;
import java.io.FileOutputStream;
import java.util.*;

/**
 * Excel数据处理器
 *
 * @author zhangxingju
 * @date 2025/03/13
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class UserDataProcessor {

    private final ExportTaskManager taskManager;

    /**
     * 临时文件目录
     */


    public boolean processData(String taskId, Map<String, Object> params) {
        ExportProgress progress = taskManager.getProgress(taskId);
        if (progress == null) {
            throw new RuntimeException("任务不存在");
        }

        try {
            // 模拟获取数据总数
            long total = 10000;

            // 更新任务状态为处理中
            taskManager.startProcessing(taskId, total);

            // 创建Excel文件
            String fileName = "export_" + taskId + ".xlsx";
            // 创建临时文件
            File tempFile = FileManager.getTempFile(taskId, fileName);

            // 导出数据到Excel
            exportToExcel(tempFile, taskId, params);

            // 更新任务状态为已完成
            taskManager.completeTask(taskId, tempFile.getAbsolutePath());

            return true;
        }
        catch (Exception e) {
            log.error("Excel data processing failed for taskId: {}", taskId, e);
            taskManager.failTask(taskId, e.getMessage());
            return false;
        }
    }

    /**
     * 导出数据到Excel
     */
    private void exportToExcel(File outputFile, String taskId, Map<String, Object> params) throws Exception {
        try (Workbook workbook = new XSSFWorkbook()) {
            Sheet sheet = workbook.createSheet("数据");

            // 创建标题行
            Row headerRow = sheet.createRow(0);
            CellStyle headerStyle = workbook.createCellStyle();
            Font headerFont = workbook.createFont();
            headerFont.setBold(true);
            headerStyle.setFont(headerFont);

            // 设置列标题
            String[] headers = {"ID", "姓名", "年龄", "邮箱", "创建时间"};
            for (int i = 0; i < headers.length; i++) {
                Cell cell = headerRow.createCell(i);
                cell.setCellValue(headers[i]);
                cell.setCellStyle(headerStyle);
                sheet.setColumnWidth(i, 15 * 256);
            }

            // 分批处理数据
            int batchSize = 1000;
            long total = 10000; // 模拟总数据量
            int rowIndex = 1;

            for (int offset = 0; offset < total; offset += batchSize) {
                // 模拟查询数据
                List<Map<String, Object>> dataList = queryData(offset, Math.min(batchSize, (int) (total - offset)));

                for (Map<String, Object> data : dataList) {
                    Row row = sheet.createRow(rowIndex++);

                    // 设置单元格值
                    setCellValue(row.createCell(0), data.get("id"));
                    setCellValue(row.createCell(1), data.get("name"));
                    setCellValue(row.createCell(2), data.get("age"));
                    setCellValue(row.createCell(3), data.get("email"));
                    setCellValue(row.createCell(4), data.get("createTime"));

                    // 更新进度
                    if (rowIndex % 100 == 0) {
                        taskManager.updateProcessed(taskId, rowIndex - 1);
                    }
                }
            }

            // 写入文件
            try (FileOutputStream outputStream = new FileOutputStream(outputFile)) {
                workbook.write(outputStream);
            }
        }
    }

    /**
     * 模拟查询数据
     */
    private List<Map<String, Object>> queryData(int offset, int limit) {
        List<Map<String, Object>> result = new ArrayList<>();
        for (int i = 0; i < limit; i++) {
            Map<String, Object> row = new HashMap<>();
            row.put("id", offset + i + 1);
            row.put("name", "测试数据 " + (offset + i + 1));
            row.put("age", 20 + (offset + i) % 50);
            row.put("email", "test" + (offset + i + 1) + "@example.com");
            row.put("createTime", new Date());
            result.add(row);
        }
        return result;
    }

    /**
     * 设置单元格值
     */
    private void setCellValue(Cell cell, Object value) {
        if (value == null) {
            cell.setCellValue("");
        }
        else if (value instanceof String) {
            cell.setCellValue((String) value);
        }
        else if (value instanceof Integer) {
            cell.setCellValue((Integer) value);
        }
        else if (value instanceof Long) {
            cell.setCellValue((Long) value);
        }
        else if (value instanceof Double) {
            cell.setCellValue((Double) value);
        }
        else if (value instanceof Date) {
            cell.setCellValue((Date) value);
        }
        else if (value instanceof Boolean) {
            cell.setCellValue((Boolean) value);
        }
        else {
            cell.setCellValue(value.toString());
        }
    }
} 